<template>
  <div class="app-container" style="height: 100%">
    <div class="app-container-inner user-import">
      <div class="btns_btn">
        <el-button style="width: 68px" @click="downloadExcelTemplate(`${route.meta.title}模板.xlsx`)">下载模板</el-button>
        <div class="dialog-btn">
          <el-select v-if="route.meta.title == '工单资料导入'" placeholder="工单模块" filterable clearable v-model="moduleId"
            :remote-method="getworkModulePageSelectChange" :loading="loading" remote remote-show-suffix>
            <el-option v-for="item in modules" :value="item.id" :disabled="item.select" :label="`${item.name}`" />
          </el-select>
          <el-button style="width: 68px" @click="selectFileDialogCancel">取消</el-button>
          <el-button style="width: 68px" class="confirm_upload_btn" :disabled="fileList.length == 0"
            @click="onUpload">确认上传</el-button>
        </div>
      </div>
      <el-upload class="upload" ref="upload" accept=".xls, .xlsx" v-model:file-list="fileList" :auto-upload="false" drag
        :limit="1" :on-exceed="handleExceed" :on-change="handleChange">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text"> 拖动文件到这 或 <em>点击上传</em> </div>
      </el-upload>
      <div class="progress_bar" v-if="dataReturned">
        <img :src="barGif" alt="" :style="`left: calc(${(Number(dataReturned?.currentProgress) || 0) * 0.8}% - 20px);`"
          class="gif_sty">
        <el-progress :stroke-width="12" :percentage="Number(dataReturned?.currentProgress) || 0" />
      </div>
      <div v-if="dataReturned" class="text_return">
        <p v-html="dataReturned.message" class="red_text"></p>
        <p>共上传成功
          <span class="tip_num">{{
          dataReturned.end
            ?dataReturned.totalCount - dataReturned.importFailtDataList.length
            : 0
        }}</span>
          条数据
        </p>
        <template v-if="dataReturned.importFailtDataList.length > 0">
          <div class="export_error">
            <el-button class="btn btn-w" type="primary"
              @click="exportToExcel(dataReturned.importFailtDataList)">失败数据(导出)</el-button>
          </div>
          <el-table border class="tableError_list" id="el-table" stripe max-height="300px" resizable
            :data="dataReturned.importFailtDataList" v-if="route.meta.title == '客户档案导入'">
            <el-table-column type="index" label="序号" width="55" fixed />
            <el-table-column show-overflow-tooltip prop="account" label="客户编码" width="130" />
            <!-- <el-table-column show-overflow-tooltip prop="username" label="账号昵称" width="130" /> -->
            <!-- <el-table-column show-overflow-tooltip prop="username" label="登录账号" width="130" /> -->
            <el-table-column show-overflow-tooltip prop="username" label="客户联系人姓名" width="130" />
            <el-table-column show-overflow-tooltip prop="phone" label="联系人手机号" width="130" />
            <el-table-column show-overflow-tooltip prop="province" label="客户地址-省" width="130" />
            <el-table-column show-overflow-tooltip prop="city" label="客户地址-市" width="130" />
            <el-table-column show-overflow-tooltip prop="area" label="客户地址-县/区" width="130" />
            <el-table-column show-overflow-tooltip prop="address" label="客户详细地址" width="130" />
            <el-table-column show-overflow-tooltip prop="userType" label="客户分类" width="130" />
            <!-- <el-table-column show-overflow-tooltip prop="username" label="知识库查看权限" width="130" /> -->
            <!-- <el-table-column show-overflow-tooltip prop="username" label="客户级别" width="130" /> -->
            <!-- <el-table-column show-overflow-tooltip prop="username" label="客户邮箱" width="130" /> -->
          </el-table>
          <el-table border class="tableError_list" id="el-table" stripe max-height="300px" resizable
            :data="dataReturned.importFailtDataList" v-if="route.meta.title == '工单资料导入'">
            <el-table-column type="index" label="序号" width="55" fixed />
            <el-table-column show-overflow-tooltip prop="username" label="客户姓名" min-width="110" />
            <el-table-column show-overflow-tooltip prop="userPhone" label="客户手机号" align="right" min-width="110" />
            <el-table-column show-overflow-tooltip prop="province" label="客户地址-省" min-width="110" />
            <el-table-column show-overflow-tooltip prop="city" label="客户地址-市" min-width="120" />
            <el-table-column show-overflow-tooltip prop="area" label="客户地址-县/区" min-width="120" />
            <el-table-column show-overflow-tooltip prop="address" label="客户详细地址" min-width="130" />
            <el-table-column show-overflow-tooltip prop="goodsModel" label="商品型号" min-width="120" />
            <el-table-column show-overflow-tooltip prop="goodsSpec" label="商品规格" min-width="120" />
            <el-table-column show-overflow-tooltip prop="status" label="状态" min-width="80" align="right" />
            <el-table-column show-overflow-tooltip prop="level" label="等级" min-width="80" />
            <el-table-column show-overflow-tooltip prop="warrantyDay" label="工单资保天数" align="right" min-width="100" />
          </el-table>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="goodsExcelImport">
import { ref, watch, onMounted } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import type { UploadInstance, UploadRawFile, UploadUserFile, UploadProps } from 'element-plus'
import { ElMessage, genFileId } from 'element-plus'
import { initWebSocket, closeWebSocket } from '../../utils/socket'
import { workModulePageSelect } from '../../api/order'
import { downloadExcelTemplate } from '../../utils/download'
import barGif from '@/assets/order/bar2.gif'
import {
  userExcelImport,
  OrderExcelImport
} from '../../api/upload'
import moment from 'moment'
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'
import * as _ from 'lodash'
import { useRoute } from 'vue-router'
const route = useRoute()
const fileList: any = ref([]) // 上传的文件
const upload = ref<UploadInstance>()
const dataReturned: any = ref(null)
// 取消
const selectFileDialogCancel = () => {
  fileList.value = []
  dataReturned.value = null
  closeWebSocket()
}
// **********工单模块下拉数据*********
const moduleId = ref()//工单模块Id
const loading = ref(false)
const modules = ref([])
const getworkModulePageSelect = (val) => {
  let data = {
    "limit": 0,
    "keyword": val,
    "page": 0
  }
  loading.value = true
  workModulePageSelect(data).then((res) => {
    if (res.data.success) {
      modules.value = res.data.data.rows
    }
    loading.value = false
  })
}
const modelValue = ref('')
const getworkModulePageSelectChange = (val) => {
  modelValue.value = val
}
watch(modelValue, (n) => {
  getworkModulePageSelect(n)
})
if (route.meta.title == '工单资料导入') {
  getworkModulePageSelect('')
}
// *****************end************
// 超出限制时执行，覆盖前一个文件
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}
const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
  selectFileDialogCancel()
  fileList.value = uploadFiles
}
// 提交文件
const onUpload = _.debounce(() => {
  if (fileList.value.length > 0) {
    if (route.meta.title == '工单资料导入' && !moduleId.value) {
      ElMessage({
        showClose: true,
        message: '先选择模块',
        type: 'warning',
      })
      return
    }
    let uuid = new Date().getTime()
    dataReturned.value = null
    initWebSocket(funProgress, `/ws/progress/${uuid}`)
    if (route.meta.title == '工单资料导入') {
      OrderExcelImport(fileList.value[0].raw, moduleId.value, uuid).then((res) => {
        if (res) {
          if (!res.data.success) {
            closeWebSocket()
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'error',
            })
          }
        }
      })
    } else if (route.meta.title == '客户档案导入') {
      userExcelImport(fileList.value[0].raw, uuid).then((res) => {
        if (res) {
          if (!res.data.success) {
            closeWebSocket()
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'error',
            })
          }
        }
      })
    }
  }
}, 600)
// 获取WebSocket返回的数据
const funProgress = (msg) => {
  dataReturned.value = msg
  // console.log(msg);
  if (msg.end) {
    closeWebSocket()
  }
}
// 准备要导出的数据   https://blog.csdn.net/qq_40036754/article/details/117228315
const exportToExcel = _.debounce((data) => {
  const wb = XLSX.utils.table_to_book(document.querySelector('#el-table'))
  const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
  try {
    FileSaver.saveAs(
      new Blob([wbout], { type: 'application/octet-stream' }),
      `上传失败数据_${moment(new Date()).format('YYYYMMDD')}.xlsx`,
    )
  } catch (e) {
    // if (typeof console !== 'undefined') console.log(e, wbout)
  }
}, 600)
</script>

<style scoped lang="scss">
.user-import {
  display: flex;
  flex-direction: column;
  flex: 1;

  :deep(.el-progress-bar) {
    width: 80% !important;
    flex: none !important;
    .el-progress-bar__inner{
      transition: all .8 !important;
    }
  }

  .progress_bar {
    width: 60% !important;
    position: relative;
    padding-top: 20px;
    margin: 0 12px;
    .gif_sty {
      position: absolute;
      top: -6px;
      left: 0;
      width: 30px;
      height: 30px;
      transition: all .8;
    }
  }

  :deep(.el-upload-dragger) {
    padding: 12px;

    .el-icon--upload {
      margin-bottom: 12px;
    }
  }

  .btns_btn {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;

    .dialog-btn {
      display: flex;
      justify-content: flex-end;
      align-items: center;

      :deep(.el-input__wrapper) {
        height: 30px;
        margin-right: 12px;
      }

      .confirm_upload_btn {
        background-color: $primaryColor;
        border-color: $primaryColor;
        color: #fff;

        &:hover {
          background-color: rgba($primaryColor, 0.8);
          border-color: rgba($primaryColor, 0.8);
        }
      }

      .btn-w {
        padding: 0 12px;
      }
    }
  }

  .text_return {
    margin: 0px 16px;

    p {
      margin: 8px 0;

      .tip_num {
        color: #007cff;
        font-size: 14px;
        padding: 0 4px;
        font-weight: bold;
      }

      &.red_text {
        color: #f56c6c;
        max-height: 200px;
        overflow: auto;
        font-size: 14px;
      }
    }

    .tableError_list {
      margin-top: 12px;
    }

    .export_error {
      display: flex;
      justify-content: end;
      align-items: center;

      .btn-w {
        padding: 0 12px;
      }
    }
  }
}
</style>
